package com.security.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.pub.model.ResponseModel;
import com.pub.util.ResponseMessage;
import com.pub.util.ResponseStatus;
import com.security.dao.model.User;
import com.security.dao.service.UserService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

@RestController
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @RequestMapping("/")
    public ResponseModel root(){
        ResponseModel responseModel = new ResponseModel();
        responseModel.setMessage("首页");
        return responseModel;
    }
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }
    @GetMapping("/login")
    public ResponseModel login(){
        ResponseModel responseModel = new ResponseModel();
        responseModel.setStatus(ResponseStatus.NO_LOGIN);
        responseModel.setMessage(ResponseMessage.NO_LOING);
        return responseModel;
    }
    @PostMapping("/api/login")
    public ResponseModel apiLogin(@RequestParam(defaultValue="") String phone,@RequestParam(defaultValue="") String password,HttpServletRequest request){
        ObjectMapper objectMapper = new ObjectMapper();
        ResponseModel responseModel = new ResponseModel();
        try {
//            JsonNode jsonNode = objectMapper.readTree(body);
//            String  phone = jsonNode.get("phone").asText();
//            String  password = jsonNode.get("password").asText();


            User user = userService.findByPhoneAndPassword(phone,password);
            if(user == null){
                responseModel.setStatus(ResponseStatus.LOING_MESSAGE);
                responseModel.setMessage(ResponseMessage.LOING_MESSAGE);
                return  responseModel;
            }
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(phone,password,user.getAuthorities());
            Authentication authentication = authenticationManager.authenticate(token);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            System.out.println(authentication);
            HttpSession session = request.getSession();
            session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());
            responseModel.setData(token);
        }catch (Exception e){
            responseModel.setError400(e.getMessage());
        }
        return responseModel;
    }

    @RequestMapping("/logout")
    public String loginOut(){
        return "登出";
    }
    @RequestMapping("/home")
    public String home(@RequestParam(value = "name")String name){
        return "首页"+name;
    }
    @RequestMapping("/401")
    public ResponseModel accesssDenied(HttpServletRequest request){
        ResponseModel responseModel = new ResponseModel();
        HashMap<String,Object> data = new HashMap<>();
        Object obj = request.getAttribute("SPRING_SECURITY_403_EXCEPTION");
        if(null != obj) {
            AccessDeniedException e = (AccessDeniedException) obj;
            data.put("message",e.getMessage());
        }
        data.put("title","错误页面");
        responseModel.setStatus(400);
        responseModel.setData(data);
        return responseModel;
    }
    @RequestMapping("/login-error")
    public ResponseModel loginError(HttpServletRequest request){
        ResponseModel responseModel = new ResponseModel();
        HashMap<String,Object> data = new HashMap<>();
        Object obj = request.getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
        if(null != obj) {
            AuthenticationException e = (AuthenticationException) obj;
            data.put("message",e.getMessage());
        }
        data.put("title","错误页面");
        responseModel.setStatus(400);
        responseModel.setData(data);
        return responseModel;
    }

    @PreAuthorize("hasAuthority('ROLE_USER')")
    @RequestMapping("/test")
    public String test(){
        return "测试";
    }
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping("/admin")
    public String admin(){
        return "管理员";
    }
}
